package com.encryption.plugin.util;

import javassist.ClassPool;
import javassist.NotFoundException;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 字节码操作工具类
 *
 * @author roseboy
 */
public class ClassUtils {

    /**
     * 加载jar包路径
     *
     * @param pool javassist的ClassPool
     * @param dir  lib路径或jar文件
     */
    public static void loadClassPath(ClassPool pool, File dir) {
        if (dir == null || !dir.exists()) {
            return;
        }

        if (dir.isDirectory()) {
            List<File> jars = new ArrayList<>();
            IoUtils.listFile(jars, dir, ".jar");
            for (File jar : jars) {
                try {
                    pool.insertClassPath(jar.getAbsolutePath());
                } catch (NotFoundException e) {
                    //ignore
                }
            }
        } else if (dir.getName().endsWith(".jar")) {
            try {
                pool.insertClassPath(dir.getAbsolutePath());
            } catch (NotFoundException e) {
                //ignore
            }
        }
    }

    public static byte[] readStream(InputStream inputStream, boolean close, String password)
            throws IOException {
        if (inputStream == null) {
            throw new IOException("Class not found");
        }
        try {
            byte[] bytes = IoUtils.toBytes(inputStream);
            byte[] bytes1 = DESUtil.decryptByte(password, bytes);
            if (bytes1 != null) {
//                try {
//                    new FileOutputStream(UUID.randomUUID().toString()+".class").write(bytes1);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
                return bytes1;
            }
            return bytes;
        } finally {
            if (close) {
                inputStream.close();
            }
        }
    }

}
